package com.itheima.mall.service.umsService;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mall.mapper.umsMapper.UmsAdminRoleRelationMapper;
import com.itheima.pojo.ums.UmsAdminRoleRelation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

@DubboService
public class UmsAdminRoleRelationServiceImpl extends ServiceImpl<UmsAdminRoleRelationMapper, UmsAdminRoleRelation> implements UmsAdminRoleRelationApi{
    @Autowired
    private UmsAdminRoleRelationMapper umsAdminRoleRelationMapper;

    /**
     * 给用户分配角色
     * @param adminId 用户ID
     * @param roleIds 角色标识数组
     * @return
     */
    @Override
    public void roleUpdate(Integer adminId, ArrayList<Integer> roleIds) {
        //根据用户ID删除原始权限
        LambdaQueryWrapper<UmsAdminRoleRelation> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsAdminRoleRelation::getAdminId,adminId);
        umsAdminRoleRelationMapper.delete(queryWrapper);
        //添加新权限
        Long id = Convert.toLong(adminId);
        for (Integer roleId : roleIds) {
            Long toLong = Convert.toLong(roleId);
            UmsAdminRoleRelation uarr= new UmsAdminRoleRelation();
            uarr.setAdminId(id);
            uarr.setRoleId(toLong);
            umsAdminRoleRelationMapper.insert(uarr);
        }
    }

    /**
     * 根据管理员ID获取对应角色IDS
     * @param adminId
     * @return
     */
    @Override
    public ArrayList<Long> getRoleIDs(Long adminId) {
        //根据管理员ID条件查询
        LambdaQueryWrapper<UmsAdminRoleRelation> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(UmsAdminRoleRelation::getAdminId,adminId);
        List<UmsAdminRoleRelation> umsAdminRoleRelations = umsAdminRoleRelationMapper.selectList(queryWrapper);
        //构建数组,循环存入数据并返回
        ArrayList<Long> res =new ArrayList<>();
        for (UmsAdminRoleRelation umsAdminRoleRelation : umsAdminRoleRelations) {
            res.add(umsAdminRoleRelation.getRoleId());
        }
        return res;
    }
}
